package com.ldc.commonlibs.http

import com.google.gson.reflect.TypeToken
import com.ldc.commonlibs.common.RspModel
import com.ldc.commonlibs.uts.ApiUtils
import com.ldc.commonlibs.uts.DataStoreUts
import com.ldc.commonlibs.uts.DialogUtils
import com.ldc.commonlibs.uts.JsonUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody

class LoinInterceptor() : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request: Request = chain.request()
        val response: Response = chain.proceed(request)
        val mediaType: MediaType? = response.body?.contentType();
        val content: String? = response.body?.string()
        val type = object : TypeToken<RspModel<Any>>() {}.type
        val data = JsonUtils.jsonToBeanByType<RspModel<Any>>("$content", type)
        if (!ApiUtils.isLogin(data.errorCode)) {
            runBlocking {
                withContext(Dispatchers.Main) {
                    DialogUtils.showLoginDialog("未登录", "【${data.errorCode}】\n${data.errorMsg}")
                }
            }
        } else {
            if (request.url.encodedPath.contains("/user/login", true)) {
                val cookies = response.headers("Set-Cookie")
                DataStoreUts.INSTANCE.setCookie("$cookies")
            }
        }
        return response.newBuilder()
            .body(content!!.toResponseBody(mediaType)).build()
    }

}